package com.kc.data.scenic.controller;

import cn.hutool.core.date.DateUtil;
import com.kc.data.common.base.BeanUtils;
import com.kc.data.common.core.AjaxResult;
import com.kc.data.common.core.controller.BaseController;
import com.kc.data.common.domain.model.KcGoodsOrderShipping;
import com.kc.data.common.domain.order.dto.BizGoodsOrderRefundDTO;
import com.kc.data.common.domain.order.dto.BizOrderStatisticsDTO;
import com.kc.data.common.domain.order.entity.BizGoodsOrder;
import com.kc.data.common.domain.order.entity.BizGoodsOrderRefund;
import com.kc.data.common.domain.order.query.BizGoodsOrderRefundQuery;
import com.kc.data.common.domain.vo.KcSendOutVO;
import com.kc.data.common.mapper.BizGoodsOrderRefundMapper;
import com.kc.data.common.page.TableDataInfo;
import com.kc.data.common.service.IBizGoodsOrderService;
import com.kc.data.common.service.IKcGoodsOrderShippingService;
import com.kc.data.common.service.ISysDictDataService;
import com.kc.data.common.utils.RocketMQTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName BizGoodsOrderController
 * @Description 订单相关Controller
 * @Author wangdongliang
 * @Date 2021/6/16 15:41
 */
@RestController
@RequestMapping("/business/goodsOrder/")
public class BizGoodsOrderController extends BaseController {
    @Resource
    private IBizGoodsOrderService bizGoodsOrderService;
    @Resource
    private ISysDictDataService dictDataService;
    @Resource
    private IKcGoodsOrderShippingService kcGoodsOrderShippingService;
    @Resource
    private BizGoodsOrderRefundMapper bizGoodsOrderRefundMapper;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 订单历史数据统计
     * @param platformId
     * @param type
     * @return
     */
    @PostMapping(value = "getOrderHistoryStatistics/{platformId}/{type}")
    public AjaxResult getOrderHistoryStatistics(@PathVariable("platformId") Integer platformId, @PathVariable("type") Integer type) {
        if(platformId == null){
            platformId = 0;
        }
        if(type == null){
            type = 0;
        }
        Date currDate = DateUtil.parse(DateUtil.now());
        BizOrderStatisticsDTO todayOrderStatisticsDTO = bizGoodsOrderService.getOrderHistoryStatistics(currDate.toString().substring(0,10),null,platformId,-type);
        BizOrderStatisticsDTO yesterdayOrderStatisticsDTO = bizGoodsOrderService.getOrderHistoryStatistics(DateUtil.yesterday().toString().substring(0,10),null,platformId,-type);
        BizOrderStatisticsDTO weekOrderStatisticsDTO = bizGoodsOrderService.getOrderHistoryStatistics(DateUtil.offsetDay(currDate, -7).toString().substring(0,10),null,platformId,-type);
        BizOrderStatisticsDTO monthOrderStatisticsDTO = bizGoodsOrderService.getOrderHistoryStatistics(DateUtil.offsetDay(currDate, -30).toString().substring(0,10),null,platformId,-type);
        Map<String,BizOrderStatisticsDTO> map = new HashMap<>();
        map.put("today",todayOrderStatisticsDTO);
        map.put("yesterday",yesterdayOrderStatisticsDTO);
        map.put("week",weekOrderStatisticsDTO);
        map.put("month",monthOrderStatisticsDTO);
        return AjaxResult.success(map);
    }

    /**
     * 按天统计成交额及成交数量
     * @return
     */
    @PostMapping(value = "getOrderHistoryStatisticsByDay/{platformId}/{type}")
    public AjaxResult getOrderHistoryStatisticsByDay(@PathVariable("platformId") Integer platformId, @PathVariable("type") Integer type) {
        if(platformId == null){
            platformId = 0;
        }
        if(type == null){
            type = 0;
        }
        Date currDate = DateUtil.parse(DateUtil.now());
        currDate = DateUtil.offsetDay(currDate, -6);
        Date tomorrow = DateUtil.offsetDay(currDate, +1);;
        List<String> dateList = new ArrayList<>();
        String currDateString = currDate.toString().substring(0,10);
        BizOrderStatisticsDTO bizOrderStatisticsDTO = bizGoodsOrderService.getOrderHistoryStatistics(currDateString,tomorrow.toString().substring(0,10),platformId,type);
        List<Integer> orderNum = new ArrayList<>();
        List<BigDecimal> orderMoney = new ArrayList<>();
        dateList.add(currDateString);
        orderNum.add(bizOrderStatisticsDTO.getOrderTotalNum());
        orderMoney.add(bizOrderStatisticsDTO.getOrderTotalMoney());
        //System.out.println("今天="+currDate+",明天="+tomorrow);
        for(int i=1;i<7;i++){
            currDate = DateUtil.offsetDay(currDate, +1);
            tomorrow = DateUtil.offsetDay(tomorrow, +1);
            currDateString = currDate.toString().substring(0,10);
            dateList.add(currDateString);
            bizOrderStatisticsDTO = bizGoodsOrderService.getOrderHistoryStatistics(currDateString,tomorrow.toString().substring(0,10),0,0);
            orderNum.add(bizOrderStatisticsDTO.getOrderTotalNum());
            orderMoney.add(bizOrderStatisticsDTO.getOrderTotalMoney());
            // System.out.println("今天="+currDate+",明天="+tomorrow);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("date",dateList);
        map.put("orderNum",orderNum);
        map.put("orderMoney",orderMoney);
        return AjaxResult.success(map);
    }

    /**
     * 订单列表
     * @param bizGoodsOrder
     * @return
     */
    @PostMapping(value = "getOrderList")
    public TableDataInfo getOrderList(@RequestBody BizGoodsOrder bizGoodsOrder) {
        //todo 默认类别为平台1（对应1游园消费 2景区好礼 3名家秒藏 4馆藏寄卖 ），其他为-1景区 -2名家 -3市场在线 -4商家
        if(bizGoodsOrder.getOrderType() == null) {
            bizGoodsOrder.setOrderType(1);
        }
        startPage();
        List<BizGoodsOrder> bizGoodsOrderList = bizGoodsOrderService.getOrderList(bizGoodsOrder);
        TableDataInfo tableDataInfo = getDataTable(bizGoodsOrderList);
        return tableDataInfo;
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @PostMapping(value = "getOrderInfo/{id}")
    public AjaxResult getOrderInfo(@PathVariable Integer id) {
        //bizGoodsOrder.setOrderType(1);
        BizGoodsOrder bizGoodsOrder = new BizGoodsOrder();
        bizGoodsOrder.setId(id);
        List<BizGoodsOrder> bizGoodsOrderList = bizGoodsOrderService.getOrderList(bizGoodsOrder);
        BizGoodsOrder goodsOrder = bizGoodsOrderList.get(0);
        //todo 处理过期秒数(待付款和已发货状态下处理)
        if(("0".equals(goodsOrder.getStatus()) || "2".equals(goodsOrder.getStatus())) && !("0000-00-00 00:00:00".equals(goodsOrder.getCloseDate()))){
            //计算毫秒
            if((goodsOrder.getCloseDate().compareTo(DateUtil.now())) >= 1) {
                goodsOrder.setCloseDateMs(DateUtil.betweenMs(DateUtil.date(), DateUtil.parse(goodsOrder.getCloseDate())));
            }
        }

        goodsOrder.setOrderProgress(Integer.parseInt(goodsOrder.getStatus())+1);
        return AjaxResult.success(goodsOrder);
    }

    /**
     * 退款列表
     * @param bizGoodsOrderRefundDTO
     * @return
     */
    @PostMapping(value = "getOrderRefundList")
    public TableDataInfo getOrderRefundList(@RequestBody BizGoodsOrderRefundDTO bizGoodsOrderRefundDTO) {
        log.info("查询参数{}",bizGoodsOrderRefundDTO);
        startPage();
        return getDataTable(bizGoodsOrderService.getRefundList(bizGoodsOrderRefundDTO));
    }

    /**
     * 退款详情
     * @param id
     * @return
     */
    @PostMapping(value = "getOrderRefundInfo/{id}")
    public AjaxResult getOrderRefundInfo(@PathVariable(value = "id") Integer id) {
        return AjaxResult.success(bizGoodsOrderService.getRefundInfo(id));
    }

    /**
     * 退款审核
     * @param bizGoodsOrderRefundQuery
     * @return
     */
    @PutMapping(value = "orderRefundCheck")
    public AjaxResult orderRefundCheck(@Valid @RequestBody BizGoodsOrderRefundQuery bizGoodsOrderRefundQuery){
        if(bizGoodsOrderRefundQuery.getStatus().equals(-1)){
            if(bizGoodsOrderRefundQuery.getRefuseRefundReason() == null || bizGoodsOrderRefundQuery.getRefuseRefundReason().equals("")){
                return AjaxResult.error("拒绝原因不能为空");
            }
        }
        return bizGoodsOrderService.orderRefundCheck(bizGoodsOrderRefundQuery);
    }

    /**
     * 订单发货
     * @param form
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    @PutMapping("/sendOut")
    @Transactional
    public AjaxResult sendOut(@Validated @RequestBody KcSendOutVO form) throws IllegalAccessException, InstantiationException {
        BizGoodsOrder bizGoodsOrder = bizGoodsOrderService.getOrderInfo(form.getOrderId());
        if ("1".equals(form.getShipType())) {
            if (form.getExpList().size() == 0) {
                return AjaxResult.error("物流不能为空");
            }
            List<KcGoodsOrderShipping> kcGoodsOrderShippingList = BeanUtils.mapsToObjects(form.getExpList().stream().map(exp -> {
                exp.put("type", "0");
                exp.put("orderId", form.getOrderId());
                return exp;
            }).collect(Collectors.toList()), KcGoodsOrderShipping.class);
            kcGoodsOrderShippingService.saveBatch(kcGoodsOrderShippingList);
        }
        bizGoodsOrder.setStatus("2");
        bizGoodsOrder.setShipType(form.getShipType());
        if(form.getExpList().size()>1){
            bizGoodsOrder.setOpenType("1");
        }else {
            bizGoodsOrder.setOpenType("0");
        }
        return AjaxResult.success(bizGoodsOrderService.updateOrderById(bizGoodsOrder));
    }

    /**
     * 订单关闭
     * @param id
     * @return
     */
    @PostMapping(value = "close/{id}")
    public AjaxResult close(@PathVariable("id") Integer id){
        BizGoodsOrder bizGoodsOrder = new BizGoodsOrder();
        bizGoodsOrder.setOrderType(1);
        bizGoodsOrder.setId(id);
        List<BizGoodsOrder> bizGoodsOrderList = bizGoodsOrderService.getOrderList(bizGoodsOrder);
        bizGoodsOrder = bizGoodsOrderList.get(0);
        bizGoodsOrder.setStatus("-1");
        return AjaxResult.success(bizGoodsOrderService.updateOrder(bizGoodsOrder));
    }

    /**
     * 确认退款操作
     * @param id
     * @return
     */
    @PutMapping(value = "confirmRefund/{id}")
    public AjaxResult confirmRefund(@PathVariable("id") Integer id){
        BizGoodsOrderRefund bizGoodsOrderRefund = new BizGoodsOrderRefund();
        bizGoodsOrderRefund.setId(id);
        bizGoodsOrderRefund = bizGoodsOrderRefundMapper.selectById(id);
        rocketMQTemplate.sendDelayMessage("goods_order_refund_auto_check",bizGoodsOrderRefund,30);
        bizGoodsOrderRefund.setStatus(5);
        bizGoodsOrderRefundMapper.updateById(bizGoodsOrderRefund);
        return AjaxResult.success(1);
    }
}
